package com.adkun.community.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CommunityUtil {

    // 生成一个随机字符串
    public static String generateUUID() {
        // java.utils.UUID
        return UUID.randomUUID().toString().replaceAll(" ", "");
    }

    // MD5加密
    // hello -> abc123def456
    // hello + 3e4a8(salt) -> abc123def456abc
    public static String md5(String key) {
        // org.apache.commons.lang3
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return DigestUtils.md5DigestAsHex(key.getBytes()); //Spring自带工具
    }

    private static final Logger logger = LoggerFactory.getLogger(CommunityUtil.class);

    /**
     * 如果文件不存在，则创建文件
     */
    public static void createFile(File dest) {
        if (!dest.exists()) {
            File tempF = dest.getParentFile();
//            int time = 0;
//            while (!tempF.exists() && !tempF.mkdir()) {
//                tempF = tempF.getParentFile();
//                ++time;
//            }
//            tempF = dest.getParentFile();
//            while (time > 0) {
//                tempF.mkdir();
//                tempF = tempF.getParentFile();
//                --time;
//            }
            tempF.mkdirs();
            try {
                dest.createNewFile();
            } catch (IOException e) {
                logger.error("创建文件失败！" + e.getMessage());
                throw new RuntimeException("创建文件失败！");
            }
        }
    }

    /**
     * 返回JSON封装字符串
     * 定义几个重载方法
     *
     * @param code
     * @param msg
     * @param map
     * @return
     */
    public static String getJSONString(int code, String msg, Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        if (map != null) {
            for (String key : map.keySet()) {
                json.put(key, map.get(key));
            }
        }
        return json.toString();
    }

    public static String getJSONString(int code, String msg) {
        return getJSONString(code, msg, null);
    }

    public static String getJSONString(int code) {
        return getJSONString(code, null, null);
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "zhangsan");
        map.put("age", "25");
        System.out.println(getJSONString(0, "ok", map));
    }

}
